import axios from 'axios';
import { getConfig, getToken, getUserInfo } from '@/utils';
import type { AxiosInstance, CreateAxiosDefaults } from 'axios';

let _httpClient: AxiosInstance | null = null;

export const lazyHttpClient = (): AxiosInstance => {
  try {
    if (!_httpClient) {
      initHttpClient({ baseURL: getConfig().serviceSettings.apiBaseUrl });
      throw new Error('httpClient is not initialized');
    }
    return _httpClient!;
  } catch (error) {
    console.error(error);
  }
  return axios.create();
};

export const initHttpClient = (config?: CreateAxiosDefaults<any>) => {
  _httpClient = axios.create({ ...config });

  _httpClient.interceptors.request.use((config) => {
    config.headers['smaptoken'] = getToken();
    config.headers['userid'] = getUserInfo()?.id || 'unknown';
    return config;
  });

  _httpClient.interceptors.response.use(async (response) => {
    return response;
  });
};
